//package com.wechat;
//
//import com.alibaba.fastjson.JSON;
//import com.alibaba.fastjson.JSONArray;
//import com.alibaba.fastjson.JSONObject;
//import com.tencent.wework.Finance;
//import com.xiaomi.appstore.common.StatErrCode;
//import com.xiaomi.appstore.crm.model.CrmWechatExternalContact;
//import com.xiaomi.appstore.crm.model.CrmWechatGroup;
//import com.xiaomi.appstore.crm.model.CrmWechatGroupLinkStaff;
//import com.xiaomi.appstore.crm.model.CrmWechatInformationConfiguration;
//import com.xiaomi.appstore.crm.model.CrmWechatMessage;
//import com.xiaomi.appstore.crm.model.CrmWechatMessageDetail;
//import com.xiaomi.appstore.crm.model.CrmWechatMessageDetailQuery;
//import com.xiaomi.appstore.crm.model.CrmWechatSeq;
//import com.xiaomi.appstore.crm.model.CrmWechatStaff;
//import com.xiaomi.appstore.crm.model.CrmWechatStaffLinkExternalUser;
//import com.xiaomi.appstore.crm.model.WechatMessageQuery;
//import com.xiaomi.appstore.crm.model.WechatMessageResult;
//import com.xiaomi.appstore.dao.master.wechat.CrmWechatSeqDAO;
//import com.xiaomi.appstore.dao.master.wechat.CrmWechatStaffLinkExternalUserDAO;
//import com.xiaomi.appstore.dao.master.wechat.WechatMessageHisToryDAO;
//import com.xiaomi.appstore.dao.slave.wechat.CrmWechatExternalContactSlaveDAO;
//import com.xiaomi.appstore.dao.slave.wechat.CrmWechatGroupLinkStaffSlaveDAO;
//import com.xiaomi.appstore.dao.slave.wechat.CrmWechatGroupSlaveDAO;
//import com.xiaomi.appstore.dao.slave.wechat.CrmWechatSeqSlaveDAO;
//import com.xiaomi.appstore.dao.slave.wechat.CrmWechatStaffSlaveDAO;
//import com.xiaomi.appstore.dao.slave.wechat.InformationConfigurationSlaveDAO;
//import com.xiaomi.appstore.dao.slave.wechat.WechatMessageHisTorySlaveDAO;
//import com.xiaomi.appstore.enums.ChatTypeEnum;
//import com.xiaomi.appstore.enums.SendPersonTypeEnum;
//import com.xiaomi.appstore.model.wechat.ChatDatas;
//import com.xiaomi.appstore.model.wechat.Qychat;
//import com.xiaomi.appstore.model.wechat.WeChatMessageHistory;
//import com.xiaomi.appstore.util.FdsUtil;
//import com.xiaomi.appstore.util.RSAUtils;
//import com.xiaomi.appstore.util.TokenUtils;
//import com.xiaomi.appstore.util.UTF8MB4;
//import com.xiaomi.appstore.util.WeChatUtils;
//import com.xiaomi.mig2.stat.StatWatcher;
//import org.apache.commons.lang3.StringUtils;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.beans.BeanUtils;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Service;
//import org.springframework.util.CollectionUtils;
//
//import java.io.File;
//import java.io.FileInputStream;
//import java.io.FileOutputStream;
//import java.io.IOException;
//import java.text.SimpleDateFormat;
//import java.time.LocalDate;
//import java.time.ZoneOffset;
//import java.time.temporal.ChronoUnit;
//import java.util.ArrayList;
//import java.util.Arrays;
//import java.util.Collections;
//import java.util.Date;
//import java.util.List;
//import java.util.Map;
//import java.util.Objects;
//import java.util.stream.Collectors;
//
//
//@Service
//public class CrmWeChatHistoryBiz {
//    private static final Logger LOGGER = LoggerFactory.getLogger(CrmWeChatHistoryBiz.class);
//    @Autowired
//    private InformationConfigurationSlaveDAO configurationSlaveDAO;
//    @Autowired
//    private WechatMessageHisToryDAO wechatMessageHisToryDAO;
//    @Autowired
//    private WechatMessageHisTorySlaveDAO wechatMessageHisTorySlaveDAO;
//    @Autowired
//    private CrmWechatStaffLinkExternalUserDAO crmWechatStaffLinkExternalUserDAO;
//    @Autowired
//    private FdsUtil fdsUtil;
//    @Autowired
//    private TokenUtils tokenUtils;
//    @Autowired
//    private WeChatUtils weChatUtils;
//    @Autowired
//    private CrmWechatSeqDAO crmWechatSeqDAO;
//    @Autowired
//    private CrmWechatSeqSlaveDAO crmWechatSeqSlaveDAO;
//    @Autowired
//    private CrmWechatStaffSlaveDAO crmWechatStaffSlaveDAO;
//    @Autowired
//    private CrmWechatExternalContactSlaveDAO crmWechatExternalContactSlaveDAO;
//    @Autowired
//    private CrmWechatGroupSlaveDAO crmWechatGroupSlaveDAO;
//    @Autowired
//    private CrmWechatGroupLinkStaffSlaveDAO crmWechatGroupLinkStaffSlaveDAO;
//
//    private static final Long LIMIT = 1000L;
//    private static final Long TIMEOUT = 5L;
//    private static final List<String> typeList = Arrays.asList("text", "image", "file", "video");
//    private static final String APP_ADAPTER_FILEPATH = "/home/work/wechat/";
//    private static final String PROXY = "proxy.market.pt.xiaomi.com:9443";
//    private static final String PUBLIC_KEY_VERSION = "5";
//
//    public WechatMessageResult queryMessageList(WechatMessageQuery messageQuery) {
//        List<String> userIdList = messageQuery.getUserId();
//        String searchCustomerName = messageQuery.getCustomerName();
//        if(!CollectionUtils.isEmpty(userIdList)){
//            List<CrmWechatGroupLinkStaff> crmWechatGroupLinkStaffList = crmWechatGroupLinkStaffSlaveDAO.selectListByStaffId(userIdList);
//            List<String> chatIdList = crmWechatGroupLinkStaffList.stream().map(CrmWechatGroupLinkStaff::getChatId).collect(Collectors.toList());
//            userIdList.addAll(chatIdList);
//            messageQuery.setUserId(userIdList);
//        }
//        if(StringUtils.isNotEmpty(searchCustomerName)){
//            ArrayList<String> customerIdList = new ArrayList<>();
//            List<String> externalUseridList = crmWechatExternalContactSlaveDAO.selectListByName(searchCustomerName);
//            List<String> chatIdList = crmWechatGroupSlaveDAO.selectListByName(searchCustomerName);
//            customerIdList.addAll(externalUseridList);
//            customerIdList.addAll(chatIdList);
//            if(!CollectionUtils.isEmpty(customerIdList)){
//                messageQuery.setCustomerIdList(customerIdList);
//            }else {
//                WechatMessageResult result = new WechatMessageResult();
//                result.setCrmWechatMessageList(Collections.emptyList());
//                result.setCount(0);
//                return result;
//            }
//        }
//        int page = messageQuery.getPage();
//        page = page - 1;
//        if (page < 0) {
//            page = 0;
//        }
//        int offset = page * messageQuery.getPageNum();
//        messageQuery.setOffset(offset);
//        List<WeChatMessageHistory> crmWechatMessages = wechatMessageHisTorySlaveDAO.pageQueryMessageList(messageQuery);
//        long count = wechatMessageHisTorySlaveDAO.queryMessageCount(messageQuery);
//
//        List<String> staffIdList = crmWechatMessages.stream().map(WeChatMessageHistory::getStaffId).collect(Collectors.toList());
//
//        List<String> customerIdList = crmWechatMessages.stream()
//                .filter(e -> Objects.equals(e.getChatType(), ChatTypeEnum.SINGLE_CHAT.getChatType()))
//                .map(WeChatMessageHistory::getCustomerId)
//                .collect(Collectors.toList());
//
//        List<String> roomIdList = crmWechatMessages.stream()
//                .filter(e -> Objects.equals(e.getChatType(), ChatTypeEnum.ROOM_CHAT.getChatType()))
//                .map(WeChatMessageHistory::getCustomerId)
//                .collect(Collectors.toList());
//
//
//        List<CrmWechatStaff> staffList = crmWechatStaffSlaveDAO.selectList(staffIdList);
//        List<CrmWechatExternalContact> externalContactList = crmWechatExternalContactSlaveDAO.selectList(customerIdList);
//        List<CrmWechatGroup> roomList = crmWechatGroupSlaveDAO.selectList(roomIdList);
//        List<CrmWechatGroupLinkStaff> crmWechatGroupLinkStaffList = crmWechatGroupLinkStaffSlaveDAO.selectListByChatId(roomIdList);
//
//        Map<String, String> staffMap = staffList.stream().collect(Collectors.toMap(CrmWechatStaff::getUserid, CrmWechatStaff::getName));
//        Map<String, String> emailMap = staffList.stream().filter(e -> StringUtils.isNotEmpty(e.getEmail())).collect(Collectors.toMap(CrmWechatStaff::getUserid, CrmWechatStaff::getEmail));
//        Map<String, String> customerMap = externalContactList.stream().collect(Collectors.toMap(CrmWechatExternalContact::getExternalUserid, CrmWechatExternalContact::getName));
//        Map<String, String> roomMap = roomList.stream().collect(Collectors.toMap(CrmWechatGroup::getChatId, CrmWechatGroup::getName));
//        Map<String, List<CrmWechatGroupLinkStaff>> groupLinkStaffMap = crmWechatGroupLinkStaffList.stream().collect(Collectors.groupingBy(CrmWechatGroupLinkStaff::getChatId));
//
//        List<CrmWechatMessage> wechatMessageList = crmWechatMessages.stream().map(e -> {
//            CrmWechatMessage message = new CrmWechatMessage();
//            String staffId = e.getStaffId();
//            String customerId = e.getCustomerId();
//            Integer chatType = e.getChatType();
//            String staffName = staffMap.getOrDefault(staffId, "小米开发服务者");
//            String email = emailMap.getOrDefault(staffId, "");
//            String newStaffName = String.format("%s(%s)", staffName, email);
//            message.setStaffName(newStaffName);
//
//            if(Objects.equals(chatType, ChatTypeEnum.SINGLE_CHAT.getChatType())){
//                String customerName = customerMap.getOrDefault(customerId, "客户");
//                message.setCustomerName(customerName);
//                if(StringUtils.isNotEmpty(staffId) && StringUtils.isNotEmpty(customerId)){
//                    CrmWechatStaffLinkExternalUser link = crmWechatStaffLinkExternalUserDAO.selectOne(staffId, customerId);
//                    if(Objects.nonNull(link)){
//                        String newCustomerName = String.format("%s(%s)", customerName, link.getAppPackageName());
//                        message.setCustomerName(newCustomerName);
//                    }
//                }
//            }else {
//                List<CrmWechatGroupLinkStaff> groupStaffList = groupLinkStaffMap.get(staffId);
//                if(!CollectionUtils.isEmpty(groupStaffList)){
//                    List<String> chatStaffIdList = groupStaffList.stream().map(CrmWechatGroupLinkStaff::getUserid).collect(Collectors.toList());
//                    List<CrmWechatStaff> crmWechatStaffList = crmWechatStaffSlaveDAO.selectList(chatStaffIdList);
//                    String chatStaffName = crmWechatStaffList.stream().map(x -> {
//                        String name = x.getName();
//                        String staffEmail = !StringUtils.isEmpty(x.getEmail()) ? x.getEmail() : "";
//                        return String.format("%s(%s)", name, staffEmail);
//                    }).collect(Collectors.joining(","));
//                    message.setStaffName(chatStaffName);
//                }
//                String roomName = roomMap.getOrDefault(customerId, "客户");
//                if(StringUtils.isEmpty(roomName)){
//                    roomName = "客户";
//                }
//                String newRoomName = String.format("%s%s", roomName, "群");
//                message.setCustomerName(newRoomName);
//            }
//            message.setStaffId(staffId);
//            message.setCustomerId(customerId);
//            message.setChatType(chatType);
//            SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM-dd");
//            message.setMsgDate(SDF.format(e.getMsgDate()));
//            return message;
//        }).collect(Collectors.toList());
//
//        WechatMessageResult result = new WechatMessageResult();
//        result.setCrmWechatMessageList(wechatMessageList);
//        result.setCount(count);
//        return result;
//    }
//
//    /**
//     * 查询聊天记录详情
//     */
//    public Map<String, List<CrmWechatMessageDetail>> queryMessageDetailMap(CrmWechatMessageDetailQuery messageQuery) {
//        String msgContent = messageQuery.getMsgContent();
//        int chatType = messageQuery.getChatType();
//        String staffId = messageQuery.getStaffId();
//        String customerId = messageQuery.getCustomerId();
//        List<WeChatMessageHistory> crmWechatMessages;
//        if (chatType == ChatTypeEnum.SINGLE_CHAT.getChatType()) {
//            crmWechatMessages = wechatMessageHisTorySlaveDAO.queryMessageDetailList(msgContent, staffId, customerId, chatType);
//        } else {
//            crmWechatMessages = wechatMessageHisTorySlaveDAO.queryMessageDetailList(msgContent, null, customerId, chatType);
//        }
//        List<CrmWechatMessageDetail> resultList = crmWechatMessages.stream().map(e -> {
//            CrmWechatMessageDetail crmWechatMessageDetail = new CrmWechatMessageDetail();
//            BeanUtils.copyProperties(e, crmWechatMessageDetail);
//            SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM-dd");
//            crmWechatMessageDetail.setMsgDate(SDF.format(e.getMsgDate()));
//            return crmWechatMessageDetail;
//        }).collect(Collectors.toList());
//        return resultList.stream().collect(Collectors.groupingBy(CrmWechatMessageDetail::getMsgDate));
//    }
//
//    /**
//     * 定时任务不断执行取聊天记录
//     */
//    public void initWechatData() {
//        CrmWechatSeq crmWechatSeq = crmWechatSeqSlaveDAO.selectSeq();
//        long seq = crmWechatSeq.getSeq();
//        String accessToken = tokenUtils.getAccessToken();
//        //获取企微信息配置
//        CrmWechatInformationConfiguration configuration = configurationSlaveDAO.queryInformationConfiguration();
//        int ret = 0;
//        long sdk = Finance.NewSdk();
//        // 初始化
//        Finance.Init(sdk, configuration.getCorpId(), configuration.getChatHistorySecret());
//        long slice = Finance.NewSlice();
//        ret = Finance.GetChatData(sdk, seq, LIMIT, PROXY, "", TIMEOUT, slice);
//        if (ret != 0) {
//            LOGGER.error("Finance GetChatData error" + ret);
//            return;
//        }
//        String data = Finance.GetContentFromSlice(slice);
//        ChatDatas cdata = JSON.parseObject(data, ChatDatas.class);
//        List<Qychat> list = cdata.getChatdata();
//        dealChatHistory(crmWechatSeq, accessToken, configuration, sdk, list);
//        Finance.FreeSlice(slice);
//    }
//
//    /**
//     * 处理聊天记录
//     */
//    private void dealChatHistory(CrmWechatSeq crmWechatSeq, String accessToken, CrmWechatInformationConfiguration configuration, long sdk, List<Qychat> list) {
//        for (Qychat qychat : list) {
//            if (!PUBLIC_KEY_VERSION.equals(qychat.getPublickey_ver())) {
//                continue;
//            }
//            //更新序号表
//            CrmWechatSeq updateCrmWechatSeq = new CrmWechatSeq();
//            updateCrmWechatSeq.setId(crmWechatSeq.getId());
//            updateCrmWechatSeq.setSeq(Long.parseLong(qychat.getSeq()));
//            updateCrmWechatSeq.setPublicKeyVer(Integer.parseInt(qychat.getPublickey_ver()));
//            crmWechatSeqDAO.updateCrmWechatSeq(updateCrmWechatSeq);
//
//            String msgs = qychat.getEncrypt_chat_msg();
//            String encryptKey = null;
//            try {
//                encryptKey = RSAUtils.getPrivateKey(qychat.getEncrypt_random_key());
//            } catch (Exception e) {
//                LOGGER.error("RSA decryption of data failed", e);
//            }
//            // 将获取到的数据进行解密操作
//            long msg = Finance.NewSlice();
//            Finance.DecryptData(sdk, encryptKey, msgs, msg);
//            String decryptMsg = Finance.GetContentFromSlice(msg);// 解密后的消息
//            LOGGER.info("decryptMsg:{}", decryptMsg);
//            JSONObject content = JSONObject.parseObject(decryptMsg);
//            String msgType = content.getString("msgtype");
//            if (!typeList.contains(msgType)) {
//                continue;
//            }
//            WeChatMessageHistory wechatMessageHistory = new WeChatMessageHistory();
//            Long msgTime = content.getLong("msgtime");
//            wechatMessageHistory.setMsgTime(msgTime);
//            wechatMessageHistory.setMsgDate(new Date(msgTime));
//            wechatMessageHistory.setMsgType(msgType);
//            wechatMessageHistory.setCreateTime(System.currentTimeMillis());
//
//            String fromUserId = content.getString("from");
//            //1客服，2客户
//            int fromUserType = 1;
//            JSONObject staffDetail = weChatUtils.getStaffDetail(accessToken, fromUserId);
//            if (staffDetail.containsKey("errcode") && (Integer) staffDetail.get("errcode") != 0) {
//                //发送者是客户
//                JSONObject extContactDetail = weChatUtils.getExtContactDetail(accessToken, fromUserId);
//                if (extContactDetail.containsKey("errcode") && (Integer) extContactDetail.get("errcode") == 0) {
//                    JSONObject external_contact = extContactDetail.getJSONObject("external_contact");
//                    String cusTomerName = external_contact.getString("name");
//                    wechatMessageHistory.setCustomerName(cusTomerName);
//                    wechatMessageHistory.setCustomerId(fromUserId);
//                    wechatMessageHistory.setSendPerson(cusTomerName);
//                    wechatMessageHistory.setSendPersonType(SendPersonTypeEnum.CUSTOMER_TYPE.getSendPersonType());
//                    fromUserType = 2;
//                } else {
//                    //发送者既不是客户也不是客服 不保存记录
//                    continue;
//                }
//            } else {
//                //发送者是客服
//                String staffName = staffDetail.getString("name");
//                wechatMessageHistory.setStaffName(staffName);
//                wechatMessageHistory.setStaffId(fromUserId);
//                wechatMessageHistory.setSendPerson(staffName);
//                wechatMessageHistory.setSendPersonType(SendPersonTypeEnum.STAFF_TYPE.getSendPersonType());
//            }
//
//            String roomId = content.getString("roomid");
//            if(!StringUtils.isEmpty(roomId)){
//                //群聊
//                wechatMessageHistory.setChatType(ChatTypeEnum.ROOM_CHAT.getChatType());
//                wechatMessageHistory.setCustomerId(roomId);
//                wechatMessageHistory.setStaffId(roomId);
//                String roomName = weChatUtils.getGroupChatInfoByRoomId(accessToken, roomId);
//                if (Objects.nonNull(roomName)) {
//                    if (StringUtils.isEmpty(roomName)) {
//                        wechatMessageHistory.setCustomerName("未命名客户群聊");
//                    } else {
//                        wechatMessageHistory.setCustomerName(roomName);
//                    }
//                } else {
//                    LOGGER.info("非客户群聊不保存");
//                    continue;
//                }
//            }else {
//                //单聊
//                wechatMessageHistory.setChatType(ChatTypeEnum.SINGLE_CHAT.getChatType());
//                JSONArray toUserListArray = content.getJSONArray("tolist");
//                List<String> toUserList = JSON.parseArray(toUserListArray.toJSONString(), String.class);
//                String toUserId = toUserList.get(0);
//                //1客服，2客户
//                int toUserType = 1;
//                JSONObject toUserDetail = weChatUtils.getStaffDetail(accessToken, toUserId);
//                if (toUserDetail.containsKey("errcode") && (Integer) toUserDetail.get("errcode") != 0) {
//                    //接受者是客户
//                    JSONObject extContactDetail = weChatUtils.getExtContactDetail(accessToken, toUserId);
//                    if (extContactDetail.containsKey("errcode") && (Integer) extContactDetail.get("errcode") == 0) {
//                        JSONObject external_contact = extContactDetail.getJSONObject("external_contact");
//                        wechatMessageHistory.setCustomerName(external_contact.getString("name"));
//                        wechatMessageHistory.setCustomerId(toUserId);
//                        toUserType = 2;
//                    } else {
//                        //接收者既不是客户也不是客服 不保存记录
//                        continue;
//                    }
//                } else {
//                    //接收者者是客服
//                    String staffName = toUserDetail.getString("name");
//                    wechatMessageHistory.setStaffName(staffName);
//                    wechatMessageHistory.setStaffId(toUserId);
//                }
//                if(fromUserType == 1 && toUserType == 1){
//                    //客服与客服之间的聊天记录不保存
//                    continue;
//                }
//                //填充包名和应用名称
//                if(StringUtils.isNotEmpty(wechatMessageHistory.getStaffId()) && StringUtils.isNotEmpty(wechatMessageHistory.getCustomerId())){
//                    CrmWechatStaffLinkExternalUser link = crmWechatStaffLinkExternalUserDAO.selectOne(wechatMessageHistory.getStaffId(), wechatMessageHistory.getCustomerId());
//                    if (Objects.nonNull(link)) {
//                        wechatMessageHistory.setAppPackageName(link.getAppPackageName());
//                        wechatMessageHistory.setAppName(link.getAppName());
//                    }
//                }
//            }
//            //上传文件
//            upLoadChatHistory(msgType, wechatMessageHistory, content, configuration, sdk);
//            StatWatcher statWatcher = new StatWatcher();
//            try {
//                statWatcher.begin("save-wechatMessageHistory");
//                //处理包含特殊字符串的内容
//                String newCustomerName = dealUtf8Mb4Str(wechatMessageHistory.getCustomerName());
//                String newMsgContent = dealUtf8Mb4Str(wechatMessageHistory.getMsgContent());
//                String newAppName = dealUtf8Mb4Str(wechatMessageHistory.getAppName());
//                wechatMessageHistory.setCustomerName(newCustomerName);
//                wechatMessageHistory.setMsgContent(newMsgContent);
//                wechatMessageHistory.setAppName(newAppName);
//                wechatMessageHisToryDAO.add(wechatMessageHistory);
//                statWatcher.end(StatErrCode.OK);
//            }catch (Exception e){
//                LOGGER.error("save wechatMessageHistory error,data:{}==error:{}", JSON.toJSONString(wechatMessageHistory), e);
//                statWatcher.end(StatErrCode.EXCEPTION);
//            }
//        }
//    }
//
//    /**
//     * 删除utf8mb4字符
//     */
//    private String dealUtf8Mb4Str(String str) {
//        if(StringUtils.isNotEmpty(str)){
//            boolean flag = UTF8MB4.containsMb4Char(str);
//            if (flag) {
//                str = UTF8MB4.replaceMb4Char(str, "");
//            }
//            return str;
//        }
//        return "";
//    }
//
//    private void upLoadChatHistory(String fileType, WeChatMessageHistory crmWechatMessage, JSONObject content, CrmWechatInformationConfiguration configuration, long sdk) {
//        //文本消息直接插入
//        if ("text".equals(fileType)) {
//            JSONObject text = content.getJSONObject("text");
//            crmWechatMessage.setMsgContent(text.getString("content"));
//            return;
//        }
//        //视频，图片，音频处理
//        String fileName = null;
//        try {
//            JSONObject jsonObject = content.getJSONObject(fileType);
//            String sdkFileId = jsonObject.getString("sdkfileid");
//            fileName = getFileName(jsonObject, fileType,crmWechatMessage);
//            if (!StringUtils.isEmpty(sdkFileId) && null != fileName) {
//                uploadFile(fileName, sdkFileId, configuration, crmWechatMessage, sdk);
//            }
//        } catch (Exception e) {
//            LOGGER.error("upLoadChatHistory Error downloading chat log file", e);
//        }
//    }
//
//    private String getFileName(JSONObject jsonObject, String fileType, WeChatMessageHistory crmWechatMessage) {
//        String fileName = null;
//        String md5sum = jsonObject.getString("md5sum");
//        switch (fileType) {
//            case "image":
//                fileName = md5sum + ".jpg";
//                crmWechatMessage.setMsgFileName(fileName);
//                crmWechatMessage.setMsgContent("图片");
//                break;
//            case "voice":
//                fileName = md5sum + ".mp3";
//                crmWechatMessage.setMsgFileName(fileName);
//                crmWechatMessage.setMsgContent("音频");
//                break;
//            case "video":
//                fileName = md5sum  + ".mp4";
//                crmWechatMessage.setMsgFileName(fileName);
//                crmWechatMessage.setMsgContent("视频");
//                break;
//            case "file":
//                fileName = jsonObject.getString("filename");
//                crmWechatMessage.setMsgFileName(fileName);
//                crmWechatMessage.setMsgContent(fileName);
//                break;
//            default:
//                fileName = "default.jpg";
//                break;
//        }
//        return fileName;
//    }
//    public void uploadFile(String fileName, String sdkFileid, CrmWechatInformationConfiguration configuration, WeChatMessageHistory crmWechatMessage, long sdk) throws IOException {
//        int ret = 0;
//        // 初始化
//        Finance.Init(sdk, configuration.getCorpId(), configuration.getChatHistorySecret());
//        String indexbuf = "";
//        String path = APP_ADAPTER_FILEPATH + fileName;
//        while (true) {
//            long mediaData = Finance.NewMediaData();
//            ret = Finance.GetMediaData(sdk, indexbuf, sdkFileid, PROXY, null, 3, mediaData);
//            if (ret != 0) {
//                Finance.FreeMediaData(mediaData);
//                return;
//            }
//            //大于512k的文件会分片拉取，此处需要使用追加写，避免后面的分片覆盖之前的数据。
//            File weChatFolder = new File(APP_ADAPTER_FILEPATH);
//            if (!weChatFolder.exists()) {
//                if (weChatFolder.mkdirs()) {
//                    LOGGER.info("create wechat folder success");
//                } else {
//                    LOGGER.error("failed create wechat folder success");
//                }
//            }
//            try (FileOutputStream outputStream = new FileOutputStream(path, true);) {
//                outputStream.write(Finance.GetData(mediaData));
//                if (Finance.IsMediaDataFinish(mediaData) == 1) {
//                    Finance.FreeMediaData(mediaData);
//                    break;
//                } else {
//                    indexbuf = Finance.GetOutIndexBuf(mediaData);
//                    Finance.FreeMediaData(mediaData);
//                }
//            } catch (Exception e) {
//                LOGGER.error("Error in pulling chat files to temporary directory", e);
//                break;
//            }
//        }
//
//        //上传到服务器
//        try (FileInputStream fileInputStream = new FileInputStream(path)) {
//            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//            String folder = "crm-content/" + sdf.format(crmWechatMessage.getMsgTime()).replace("-", "/") + "/";
//            String objectPath = fdsUtil.uploadFile(folder + fileName, fileInputStream);
//            String url = fdsUtil.generateDownloadUrl(objectPath);
//            crmWechatMessage.setMsgFileUrl(url);
//        } catch (Exception e) {
//            LOGGER.error("Upload wechat file to FDS error", e);
//        }
//
//        //删除临时文件夹的文件
//        File tempFile = new File(path);
//        if (tempFile.delete()) {
//            LOGGER.info("wechat temporary file deleted successfully:{}", fileName);
//        } else {
//            LOGGER.error("wechat temporary file deleted failed:{}", fileName);
//        }
//        LOGGER.info("Download file success:{}", fileName);
//    }
//
//    public void dealChatHistoryData(){
//        LocalDate currentDate = LocalDate.now();
//        LocalDate sixMonthsAgo = currentDate.minus(6, ChronoUnit.MONTHS);
//        long msgTime = sixMonthsAgo.atStartOfDay(ZoneOffset.ofHours(8)).toInstant().toEpochMilli();
//        List<WeChatMessageHistory> expiredList = wechatMessageHisTorySlaveDAO.queryExpiredMessageDetailList(msgTime);
//        if(!CollectionUtils.isEmpty(expiredList)){
//            List<Long> expiredIdList = expiredList.stream().map(WeChatMessageHistory::getId).collect(Collectors.toList());
//            LOGGER.info("expired message history,expiredIdList=={}", expiredIdList);
//            wechatMessageHisToryDAO.addHisList(expiredList);
//            wechatMessageHisToryDAO.deleteByIdList(expiredIdList);
//        }
//    }
//}
